﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;

namespace TA.DotNetUtils
{
	public static class DirectoryUtility
	{
		static char[] PossibleDelimiters = new char[] { '/', '\\' };
		static char GetDelimiter(string path)
		{
			bool all = true;
			foreach (char delim in PossibleDelimiters)
			{
				if (!path.Contains(delim))
					all = false;
			}
			if (all)
				throw new ArgumentException(string.Format("The path '{0}' contains more than one type of delimiters (ie., only '/' or '\\' - not both).", path));
			foreach (char delim in PossibleDelimiters)
			{
				if (path.Contains(delim))
					return delim;
			}
			return char.MinValue;
		}
		public static string CombinePath(params string[] paths)
		{
			if (paths.Length < 2) throw new ArgumentException("Path list has to contain at least 2 parameters.");
			char[] delims = new char[paths.Length];
			char commonDelim = char.MinValue;
			for (int i = 0; i < paths.Length; ++i)
			{
				if (paths[i] == null) continue;

				delims[i] = GetDelimiter(paths[i]);

				if (delims[i] != char.MinValue)
				{
					if (commonDelim == char.MinValue)
						commonDelim = delims[i];
					else
					{
						if (commonDelim != delims[i])
							throw new ArgumentException("Paths with differing delimiters can not be combined.");
					}
				}
			}

			string temp = string.Join(commonDelim.ToString(), paths);
			string doubleDelim = commonDelim.ToString() + commonDelim.ToString();
			while (temp.IndexOf(doubleDelim, 1) != -1)
				temp = temp[0].ToString() + temp.Substring(1).Replace(doubleDelim, commonDelim.ToString());
			return temp;
		}
		static Regex rgxPath = new Regex(@"([^:\\]+)(?!:)");
		/// <summary>
		/// 
		/// </summary>
		/// <param name="path">Path ending with a '\'.</param>
		public static void EnsurePathExists(string path)
		{
			if (path == null) throw new ArgumentNullException("path");

			MatchCollection mclPathParts = rgxPath.Matches(path);
			if (mclPathParts.Count == 0) return;
			StringBuilder sbCurPath = new StringBuilder(path.Substring(0, mclPathParts[0].Index));
			foreach (Match m in mclPathParts)
			{
				sbCurPath.Append(m.Value);
				sbCurPath.Append("\\");
				if (!Directory.Exists(sbCurPath.ToString()))
					Directory.CreateDirectory(sbCurPath.ToString());
			}
		}
	}
}
